<template>
    <div class="tab-content">
        <!-- 标点列表 -->
        <div class="map-points-header">
            <h3>地图标点列表</h3>
            <div class="header-buttons">
                <el-button type="primary" @click="openAddPointDialog">添加标点</el-button>
            </div>
        </div>

        <el-table :data="securityForm.mapPoints" border style="width: 100%; margin-bottom: 20px;">
            <el-table-column prop="name" label="点位名称" align="center"/>
            <!-- 图标 -->
            <el-table-column label="图标" align="center">
                <template #default="{ row }">
                    <div style="width: 100%;display: flex;justify-content: center;">
                        <img v-if="row.icon" :src="row.icon" alt="图标" style="width: 30px; height: 30px; object-fit: cover; border-radius: 4px;" />
                        <span v-else style="color: #999;">无图标</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="longitude" label="经度" align="center"/>
            <el-table-column prop="latitude" label="纬度" align="center"/>
            <el-table-column label="操作">
                <template #default="{ row, $index }">
                    <el-button size="small" type="primary" @click="editPoint(row, $index)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deletePoint($index)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        

        <!-- 标点配置弹窗 -->
        <el-dialog v-model="pointDialogVisible" title="标点配置" width="1200px" class="point-dialog" style="height: 80vh;">
            <div class="dialog-content">
                <div class="form-section">
                    <h4>标点信息</h4>
                    <el-form ref="pointFormRef" :model="pointForm" :rules="pointRules" label-width="100px">
                        <el-form-item label="点位名称" prop="name">
                            <el-input v-model="pointForm.name" placeholder="请输入点位名称" />
                        </el-form-item>
                        
                        <el-form-item label="经度" prop="longitude">
                            <el-input-number v-model="pointForm.longitude" :precision="6"
                                placeholder="请输入经度" style="width: 100%" />
                        </el-form-item>
                        <el-form-item label="纬度" prop="latitude">
                            <el-input-number v-model="pointForm.latitude" :precision="6" placeholder="请输入纬度"
                                style="width: 100%" />
                        </el-form-item>
                        <el-form-item label="图标" prop="icon">
                            <div class="icon-upload-section">
                                <div v-if="pointForm.icon" class="current-icon">
                                    <img :src="pointForm.icon" style="width: 50px; height: 50px; object-fit: cover; border: 1px solid #ddd; border-radius: 4px;" />
                                </div>
                                <UploadComponent 
                                    :type="'image'" 
                                    :multiple="false" 
                                    :limit="1"
                                    @success="handleIconUpload">
                                    <el-button type="primary">{{ pointForm.icon ? '更换图标' : '上传图标' }}</el-button>
                                </UploadComponent>
                            </div>
                        </el-form-item>
                    </el-form>
                </div>

                <div class="map-section">
                    <h4>地图选点</h4>
                    <div id="amap-container" class="amap-container"></div>
                    <div class="map-actions">
                        <el-button type="primary" @click="getLocationFromMap">初始化地图/重新获取</el-button>
                        <!-- <el-button @click="destroyMap">清除地图</el-button> -->
                    </div>
                </div>
            </div>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancelPoint">取消</el-button>
                    <el-button type="primary" @click="savePoint">确定</el-button>
                </span>
            </template>
        </el-dialog>



        <div class="save-button-container">
            <el-button type="primary" @click="saveSecurityData">保存地图标点配置</el-button>
        </div>
    </div>
</template>
<script lang="ts" setup>
    import { ref, reactive } from 'vue'
    import { ElMessage, ElMessageBox } from 'element-plus'
    import { Plus } from '@element-plus/icons-vue'
    import { updateDataClassify } from '@/api/port'
    import AMapLoader from '@amap/amap-jsapi-loader'
    import UploadComponent from '@/components/upload/index.vue'

    // 定义
    // 模块8: 地图标点配置表单（高德地图版本）
    const securityForm = reactive({
        mapPoints: [] as Array<{
            name: string
            longitude: number
            latitude: number
            icon: string
        }>
    })
    
    
    // 规则
    const pointRules = {
        name: [{ required: true, message: '点位名称不能为空', trigger: 'blur' }],
        longitude: [{ required: true, message: '经度不能为空', trigger: 'blur' }],
        latitude: [{ required: true, message: '纬度不能为空', trigger: 'blur' }],
        icon: [{ required: true, message: '图标不能为空', trigger: 'blur' }],

    }
    
    // 地图相关状态
    const mapInstance = ref<any>(null)
    const mapLoaded = ref(false)
    // 标点配置弹窗相关
    const pointDialogVisible = ref(false)
    const currentPointIndex = ref(-1)
    const pointForm = reactive({
        name: '',
        longitude: 0,
        latitude: 0,
        icon: ''
    })

    
    
    
    const handleIconUpload = (response: any) => {
        console.log(response)

        if (response.data && response.data.url) {
            // pointTypeForm.icon = response.data.uri
            pointForm.icon = response.data.uri
            ElMessage.success('图标上传成功')
        }
    }
    
    const removeIcon = () => {
        ElMessage.success('图标已删除')
    }
    
    // 地图标点相关函数
    const openAddPointDialog = async () => {
        currentPointIndex.value = -1
        pointForm.name = ''
        pointForm.longitude = 0
        pointForm.latitude = 0
        pointDialogVisible.value = true
        let timer = setTimeout(() => {
            getLocationFromMap()
            clearTimeout(timer)
        }, 500)
    }

    // 从地图获取坐标
    const getLocationFromMap = () => {
        // 初始化地图（如果还未初始化）
        if (!mapInstance.value && !mapLoaded.value) {
            initMap()
        } else {
            ElMessage.info('请点击地图获取坐标')
        }
    }

    // 初始化高德地图
    const initMap = async () => {
        try {
            // 设置安全密钥 - 必须在AMapLoader.load之前设置
            window._AMapSecurityConfig = {
                securityJsCode: import.meta.env.VITE_AMAP_SECURITY_KEY || '587b22815e6cc6b14effaa607c627fb7'
            }

            // 使用AMapLoader加载高德地图API
            const AMap = await AMapLoader.load({
                key: import.meta.env.VITE_AMAP_KEY || 'e6072f86d2d66d78671eaa4542006354', // 高德地图Web端开发者Key
                version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                plugins: ['AMap.ToolBar', 'AMap.Scale'] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
            })

            // 创建地图容器
            const mapContainer = document.getElementById('amap-container')
            if (!mapContainer) {
                ElMessage.error('地图容器未找到')
                return
            }

            // 初始化地图
            const map = new AMap.Map('amap-container', {
                zoom: 12, // 级别
                center: [117.420507, 37.827724], // 中心点坐标，北京
                viewMode: '2D' // 使用2D视图
            })

            mapInstance.value = map
            mapLoaded.value = true

            // 添加地图点击事件监听
            map.on('click', (e: any) => {
                const lnglat = e.lnglat
                pointForm.longitude = Number(lnglat.getLng().toFixed(6))
                pointForm.latitude = Number(lnglat.getLat().toFixed(6))
                ElMessage.success(`已获取坐标：${pointForm.longitude}, ${pointForm.latitude}`)
            })

            ElMessage.success('地图初始化成功，请点击地图获取坐标')
        } catch (error) {
            console.error('地图初始化失败:', error)
            ElMessage.error('地图初始化失败，请检查网络连接或API密钥')
        }
    }

    // 销毁地图实例
    const destroyMap = () => {
        if (mapInstance.value) {
            mapInstance.value.destroy()
            mapInstance.value = null
            mapLoaded.value = false
        }
    }
    // 取消按钮
    const cancelPoint = () => {
        pointDialogVisible.value = false
        destroyMap()
    }


    // 编辑点位
    const editPoint = (point: any, index: number) => {
        currentPointIndex.value = index
        pointForm.name = point.name
        pointForm.longitude = point.longitude
        pointForm.latitude = point.latitude
        pointDialogVisible.value = true
        let timer = setTimeout(() => {
            getLocationFromMap()
            clearTimeout(timer)
        }, 500)
    }
    // 删除点位
    const deletePoint = (index: number) => {
        ElMessageBox.confirm('确定要删除这个标点吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            securityForm.mapPoints.splice(index, 1)
            ElMessage.success('删除成功')
        })
    }


    const pointFormRef = ref()
    const savePoint = async () => {
        if (!pointFormRef.value) return
        
        try {
            await pointFormRef.value.validate()
            
            const pointData = {
                name: pointForm.name,
                longitude: pointForm.longitude,
                latitude: pointForm.latitude,
                icon: pointForm.icon
            }

            if (currentPointIndex.value >= 0) {
                // 编辑模式
                securityForm.mapPoints[currentPointIndex.value] = pointData
                ElMessage.success('标点更新成功')
            } else {
                // 新增模式
                securityForm.mapPoints.push(pointData)
                ElMessage.success('标点添加成功')
            }

            pointDialogVisible.value = false
        } catch (error) {
            ElMessage.warning('请填写完整的标点信息')
        }
    }


    const securityFormRef = ref()
    const saveSecurityData = async () => {
        if (securityForm.mapPoints.length === 0) {
            ElMessage.warning('请至少添加一个地图标点')
            return
        }
        
        await updateDataClassify({
            id: 3,
            key: 'module8',
            value: securityForm
        })
        console.log('保存地图标点配置:', securityForm)
        ElMessage.success('地图标点配置保存成功')
    }

    const init = async (module: any) => {
        if (module) {
            securityForm.mapPoints = module.mapPoints
        }
    }

    defineExpose({
        init
    })
</script>
<style scoped>
.tab-content {
    padding: 20px;
}

.map-points-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.map-points-header h3 {
    margin: 0;
    color: #333;
}

.point-dialog .dialog-content {
    height: 100%;
    width: 100%;
    display: flex;
    gap: 20px;
}

.point-dialog .dialog-content .form-section {
    flex: 1;
}

.point-dialog .dialog-content .form-section h4 {
    margin-bottom: 15px;
    color: #333;
    border-bottom: 1px solid #eee;
    padding-bottom: 8px;
}

.point-dialog .dialog-content .map-section {
    flex: 2;
}

.point-dialog .dialog-content .map-section h4 {
    margin-bottom: 15px;
    color: #333;
    border-bottom: 1px solid #eee;
    padding-bottom: 8px;
}

.point-dialog .dialog-content .map-section .amap-container {
    width: 100%;
    height: calc(100% - 100px);
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-bottom: 10px;
}

.point-dialog .dialog-content .map-section .map-actions {
    display: flex;
    gap: 10px;
    justify-content: center;
}

.save-button-container {
    text-align: center;
    margin-top: 20px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>